package keeto.com.vn.classified.ui;

import java.util.ArrayList;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classfied.model.Category;
import keeto.com.vn.classified.adapter.AdapterProductViewAll;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.menutab.IMenuTabConfig;
import keeto.com.vn.classified.menutab.MenuTabAdapter;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.network.entity.ListItemEntity;
import keeto.com.vn.classified.widgets.LogoutDialog;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.androidquery.AQuery;
import com.androidquery.util.AQUtility;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;


public class ListCateproductActivity extends Activity implements
OnClickListener, OnRefreshListener<ListView> {
	private final static String VIEW_ALL_PRODUCT_NEWEST = "product_new";
	private final static String VIEW_ALL_PRODUCT_PROPOSED = "product_same";
	private final static String VIEW_ALL_PRODUCT_SAME_COST = "product_same_cost";
	private final static String VIEW_ALL_PRODUCT_SAME_TYPE = "product_same_type";
	private final static String PRODUCT_KEY = "products";
	private final static String TITLE_KEY = "title";
	private final static String CATEGORY_KEY = "Category";


	private DrawerLayout drawerLayoutMenuTab;
	private ListView mDrawerList;
	private MenuTabAdapter tabAdapter;
	private Area mArea = null;
	private ImageButton ib_title_na_menu;
	private ImageButton ib_title_logo_home;
	private ImageView iv_title_search_home;
	private Button btn_editor_warranty;
	private EditText edt_search_warranty_store;
	private ImageButton btn_search_warranty;
	private TextView tv_cate_product;
	private PullToRefreshListView lv_list_product;
	private ProgressBar pb_pg_load;
	private static String cate = "";
	private String cateName;
	private static InUIThreadHandler mReturnCodeHandler = null;
	private int pageCount = 1;
	private int PAGE_LIMIT = 10;
	private AdapterProductViewAll mAdapter;
	private Bundle extras;
	private Intent intent;
	private Category  mCategory;
	private String mTitle;

	private int PageNumber = 1;
	private boolean resetSortBy = false;

	int GuarranteeStoreID;
	String CateID;
	int action = -1;
	private String Action;
	private ViewAllListener mListener = new ViewAllListener();
	private String SortBy = "";
	private BuiltinService builtservice = null;
	private BuiltinServiceManager mBuiltinServiceManager = null;
	private AQuery mQuery;

	private static ArrayList<ListItemEntity> arrProduct = new ArrayList<ListItemEntity>();

	public static void actionLaunch(Context context, String str_cate) {
		Intent intent = new Intent(context, ListCateproductActivity.class);
		cate = str_cate;
		intent.setAction(VIEW_ALL_PRODUCT_NEWEST);
		intent.putExtra("str_cate", str_cate);
		context.startActivity(intent);
	}

	public static void actionLaunchCateName(Context context, String title, Category category) {
		Intent intent = new Intent(context, ListCateproductActivity.class);
		intent.putExtra(TITLE_KEY, title);
		intent.putExtra(CATEGORY_KEY, category);
		intent.setAction(VIEW_ALL_PRODUCT_PROPOSED);
		context.startActivity(intent);
	}

	public static void actionLaunchCate(Context context, String str_cate,
			String categoryID, int GuaranteeStoreID, String NotInPCodes) {
		Intent intent = new Intent(context, ListCateproductActivity.class);
		intent.putExtra("str_cate", str_cate);
		intent.putExtra("categoryID", categoryID);
		intent.putExtra("GuaranteeStoreID", GuaranteeStoreID);
		intent.putExtra("NotInPCodes", NotInPCodes);
		intent.setAction(VIEW_ALL_PRODUCT_SAME_TYPE);
		context.startActivity(intent);
	}

	public static void actionLaunchViewAllSameCost(Context context,
			String str_cate, String cost, String CateID, int GuarranteeStoreID,
			String NotInPCodes) {
		Intent intent = new Intent(context, ListCateproductActivity.class);
		intent.putExtra("str_cate", str_cate);
		intent.putExtra("Cost", cost);
		intent.putExtra("CateID", CateID);
		intent.putExtra("GuarranteeStoreID", GuarranteeStoreID);
		intent.putExtra("NotInPCodes", NotInPCodes);
		intent.setAction(VIEW_ALL_PRODUCT_SAME_COST);
		context.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.list_cate_product_layout);
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		mArea = IAManager.getInstance(getApplicationContext()).getMyArea();
		mQuery = new AQuery(this);
		initUIComponent();
		initMenuData();
		onNewIntent(getIntent());
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (tabAdapter != null && mCategory != null){
			for (int i=0;i<tabAdapter.getTabModel().size();i++){
				if (tabAdapter.getTabModel().get(i).getMenutab_key() == IMenuTabConfig.MENU_HOME){
					tabAdapter.getTabModel().get(i).setNameMenu(mCategory.getName());
					break;
				}
			}
			tabAdapter.notifyDataSetChanged();
		}
	}

	private void initUIComponent() {
		ib_title_na_menu = (ImageButton) findViewById(R.id.btn_title_na_menu);
		ib_title_logo_home = (ImageButton) findViewById(R.id.btn_title_logo_home);
		iv_title_search_home = (ImageView) findViewById(R.id.btn_title_search_home);

		ib_title_na_menu.setOnClickListener(this);
		ib_title_logo_home.setOnClickListener(this);
		iv_title_search_home.setOnClickListener(this);

		drawerLayoutMenuTab = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.drawer);

		pb_pg_load = (ProgressBar) findViewById(R.id.pg_load);
		tv_cate_product = (TextView) findViewById(R.id.cate_product);
		lv_list_product = (PullToRefreshListView) findViewById(R.id.list_product);
		lv_list_product.setMode(Mode.BOTH);
		lv_list_product.setPullToRefreshOverScrollEnabled(true);
		// search
		btn_editor_warranty = (Button) findViewById(R.id.btn_editor_warranty);
		btn_search_warranty = (ImageButton) findViewById(R.id.btn_search_warranty);
		edt_search_warranty_store = (EditText) findViewById(R.id.edt_search_warranty_store);
		btn_search_warranty.setOnClickListener(this);
		btn_editor_warranty.setOnClickListener(this);

		edt_search_warranty_store.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
					String keysearch = edt_search_warranty_store.getText().toString();
					if (mCategory != null){
						ProductsActivity.actionSearchByCategory(ListCateproductActivity.this, mCategory.getRemoteId(), keysearch);
					}else{
						ProductsActivity.actionSearchGlobalbyKey(ListCateproductActivity.this, keysearch);
					}
				}
				return false;
			}
		});



		mAdapter = new AdapterProductViewAll(this, arrProduct, mQuery);
		lv_list_product.setAdapter(mAdapter);
		mAdapter.notifyDataSetChanged();
		lv_list_product.setOnRefreshListener(this);

	}

	private void initMenuData(){
		if (builtservice == null){
			tabAdapter = new MenuTabAdapter(ListCateproductActivity.this, false,IMenuTabConfig.MENU_HOME);
		}else{
			tabAdapter = new MenuTabAdapter(ListCateproductActivity.this, true,IMenuTabConfig.MENU_HOME);
			tabAdapter.setUsername(builtservice.getUserName());
		}
		mDrawerList.setAdapter(tabAdapter);
		mDrawerList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (tabAdapter.getTabModel() != null){
					int index = tabAdapter.getTabModel().get(position).getMenutab_key();
					switch (index) {
					case IMenuTabConfig.MENU_HOME:
						drawerLayoutMenuTab.closeDrawers();
						CategoriesActivity.launchCategoriesView(ListCateproductActivity.this, mArea);
						break;
					case IMenuTabConfig.MENU_AREA:
						drawerLayoutMenuTab.closeDrawers();
						ProvincesActivity.actionChangeCityLaunch(ListCateproductActivity.this);
						break;
					case IMenuTabConfig.MENU_PROFILE_NAME:
						if(builtservice==null){
							drawerLayoutMenuTab.closeDrawers();
							LoginActivity.actionLaunch(ListCateproductActivity.this);
						}else{
							drawerLayoutMenuTab.closeDrawers();
							UserProfileActivity.actionLaunch(ListCateproductActivity.this);
						}

						break;
					case IMenuTabConfig.MENU_INTEREST:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewFavorites(ListCateproductActivity.this);
						break;
					case IMenuTabConfig.MENU_POSTED:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewPosted(ListCateproductActivity.this);
						break;
					case IMenuTabConfig.MENU_HISTORY:
						drawerLayoutMenuTab.closeDrawers();
						FavoritesActivity.actionViewHistory(ListCateproductActivity.this);

						break;
					case IMenuTabConfig.MENU_LOGOUT:
						drawerLayoutMenuTab.closeDrawers();
						LogoutDialog dialog= new LogoutDialog(ListCateproductActivity.this);
						dialog.show();
						break;

					case IMenuTabConfig.MENU_POST:
						drawerLayoutMenuTab.closeDrawers();
						PostProductActivity.actionLaunch(ListCateproductActivity.this);
						break;

					default:
						break;
					}

				}
			}
		});

	}


	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
		Action = intent.getAction();
		extras = intent.getExtras();
		if (Action.equals(VIEW_ALL_PRODUCT_NEWEST)) {
			action = 0;
			if (cate.equals(this.getResources().getString(
					R.string.ia_raovat_moinhat))) {
				SortBy = "1";
				tv_cate_product.setText(cate);
			} else if (cate.equals(this.getResources().getString(
					R.string.ia_raovat_quantamnhat))) {
				SortBy = "3";
				tv_cate_product.setText(cate);
			} else if (cate.equals(this.getResources().getString(
					R.string.ia_raovat_danhgiacao))) {
				SortBy = "2";
				tv_cate_product.setText(cate);
			}
			arrProduct.clear();
			mAdapter.notifyDataSetChanged();
			ClassifiedCore.getInstance(this.getApplication())
			.taskGetAndroidProductAd(mListener, +PAGE_LIMIT, SortBy,
					PageNumber, mArea.getRemoteId());
		} else if (Action.equals(VIEW_ALL_PRODUCT_PROPOSED)) {
			action = 1;
			mTitle = extras.getString(TITLE_KEY);	
			tv_cate_product.setText(mTitle);
			mCategory = (Category) extras.get(CATEGORY_KEY);
			btn_editor_warranty.setText(mCategory.getName());
			edt_search_warranty_store.setHint(mCategory.getName());

			arrProduct.clear();
			mAdapter.notifyDataSetChanged();
			ClassifiedCore.getInstance(ListCateproductActivity.this)
			.taskGetAndroidProductProposed(mListener,
					mArea.getRemoteId(), "", "5", PAGE_LIMIT,
					PageNumber, "products", mCategory.getRemoteId());
		} else if (Action.equals(VIEW_ALL_PRODUCT_SAME_COST)) {
			String text=extras.getString("str_cate");
			tv_cate_product.setText(text);
			action = 2;
			String CateID = extras.getString("CateID");
			String cost = extras.getString("Cost");
			int GuaranteeStoreID = extras.getInt("GuaranteeStoreID");
			String NotInPCodes = extras.getString("NotInPCodes");
			arrProduct.clear();
			ClassifiedCore.getInstance(ListCateproductActivity.this)
			.taskGetAndroidProductSameCost(mListener, CateID,
					GuaranteeStoreID + "", "", PAGE_LIMIT, PageNumber,
					"products", false, NotInPCodes, cost);

		} else if (Action.equals(VIEW_ALL_PRODUCT_SAME_TYPE)) {
			action = 3;
			String text=extras.getString("str_cate");
			tv_cate_product.setText(text);
			String CateID = extras.getString("categoryID");
			int GuaranteeStoreID = extras.getInt("GuaranteeStoreID");
			String NotInPCodes = extras.getString("NotInPCodes");
			arrProduct.clear();
			ClassifiedCore.getInstance(ListCateproductActivity.this)
			.taskGetAndroidProductType(mListener, CateID,
					GuaranteeStoreID + "", "", 10, PageNumber,
					"products", false, NotInPCodes);

		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_title_na_menu:
			if (drawerLayoutMenuTab.isDrawerOpen(mDrawerList)) {
				drawerLayoutMenuTab.closeDrawers();
			} else {
				drawerLayoutMenuTab.openDrawer(mDrawerList);
			}
			break;
		case R.id.btn_title_search_home:
			ProductsActivity.actionSearchGlobal(this);
			break;
		case R.id.btn_title_logo_home:
			HomeClassifeldActivity.actionLaunch(this);
			break;
		case R.id.btn_editor_warranty:
			CategoriesActivity.launchCategoriesView(ListCateproductActivity.this, mArea);
			break;
		case R.id.btn_search_warranty:
			String keysearch = edt_search_warranty_store.getText().toString();
			if (action==1) {
				ProductsActivity.actionSearchByCategory(this,  mCategory.getRemoteId(), keysearch);
			}else{
				ProductsActivity.actionSearchGlobalbyKey(ListCateproductActivity.this,keysearch);
			}
		
			break;
		default:
			break;
		}
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == ProvincesActivity.ACTION_CHANGE_AREA && resultCode == RESULT_OK){
			mArea =  IAManager.getInstance(this).getMyArea();
			if (tabAdapter != null && mArea != null){
				for (int i=0;i<tabAdapter.getTabModel().size();i++){
					if (tabAdapter.getTabModel().get(i).getMenutab_key() == IMenuTabConfig.MENU_AREA){
						tabAdapter.getTabModel().get(i).setNameMenu(mArea.getName());
						break;
					}
				}
				tabAdapter.notifyDataSetChanged();
				PageNumber = 1;
				arrProduct.clear();
				mAdapter.notifyDataSetChanged();
				switch (action) {
				case 0:
					ClassifiedCore.getInstance(this.getApplication()).taskGetAndroidProductAd(mListener, PAGE_LIMIT,
							SortBy, PageNumber, mArea.getRemoteId());
					break;
				case 1:
					String CateID = extras.getString("categoryID");
					ClassifiedCore.getInstance(this.getApplication()).taskGetAndroidProductAd(mListener, PAGE_LIMIT,
							SortBy, PageNumber, mArea.getRemoteId());
					break;
				case 2:
					CateID = extras.getString("CateID");
					String cost = extras.getString("Cost");
					int GuaranteeStoreID = extras.getInt("GuaranteeStoreID");
					String NotInPCodes = extras.getString("NotInPCodes");
					ClassifiedCore.getInstance(ListCateproductActivity.this).taskGetAndroidProductSameCost(mListener, CateID,
							GuaranteeStoreID + "", "", PAGE_LIMIT, PageNumber,"products", false, NotInPCodes, cost);
					break;
				case 3:
					CateID = extras.getString("categoryID");
					GuaranteeStoreID = extras.getInt("GuaranteeStoreID");
					NotInPCodes = extras.getString("NotInPCodes");
					ClassifiedCore.getInstance(ListCateproductActivity.this).taskGetAndroidProductType(mListener, CateID,
							GuaranteeStoreID + "", "", 10, PageNumber,"products", false, NotInPCodes);
					break;

				default:
					break;
				}
			}
		}
	}
	class ViewAllListener extends ClassifiedListener {

		@Override
		public void finishgetAndroidProductProposed(final int returnCode,
				ArrayList<ListItemEntity> listPromotions,
				ArrayList<ListItemEntity> listSuggest,
				final ArrayList<ListItemEntity> listSuggestProduct,
				ArrayList<ListItemEntity> listFavorite, final boolean hasMore,
				final int pageCount) {
			// TODO Auto-generated method stub
			super.finishgetAndroidProductProposed(returnCode, listPromotions,
					listSuggest, listSuggestProduct, listFavorite, hasMore,
					pageCount);
			runOnUiThread(new Runnable() {
				public void run() {
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						if (PageNumber < pageCount) {
							PageNumber += 1;
						} else {
							PageNumber = -1;
						}
						if (listSuggestProduct != null
								&& listSuggestProduct.size() > 0) {
							arrProduct.addAll(listSuggestProduct);
						}

					} else {
						mReturnCodeHandler.takeActionByReturnCode(
								ListCateproductActivity.this, returnCode, true);
					}
					mAdapter.notifyDataSetChanged();
					lv_list_product.onRefreshComplete();
					pb_pg_load.setVisibility(View.GONE);
				}

			});
		}

		@Override
		public void finishGetAndroidProductType(final int returnCode,
				final ArrayList<ListItemEntity> listProductType,
				final int pageCount) {
			// TODO Auto-generated method stub
			super.finishGetAndroidProductType(returnCode, listProductType,
					pageCount);
			runOnUiThread(new Runnable() {
				public void run() {
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						if (PageNumber < pageCount) {
							PageNumber += 1;
						} else {
							PageNumber = -1;
						}
						arrProduct.addAll(listProductType);
						mAdapter.notifyDataSetChanged();
					}
					lv_list_product.onRefreshComplete();
					pb_pg_load.setVisibility(View.GONE);
				}
			});
		}

		@Override
		public void finishGetAndroidProductSameCost(final int returnCode,
				final ArrayList<ListItemEntity> listProductType,
				final int pageCount) {
			// TODO Auto-generated method stub
			super.finishGetAndroidProductSameCost(returnCode, listProductType,
					pageCount);
			runOnUiThread(new Runnable() {
				public void run() {
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						if (PageNumber < pageCount) {
							PageNumber += 1;
						} else {
							PageNumber = -1;
						}
						arrProduct.addAll(listProductType);
						mAdapter.notifyDataSetChanged();
					}
					lv_list_product.onRefreshComplete();
					pb_pg_load.setVisibility(View.GONE);
				}
			});
		}

		@Override
		public void finishGetProductAd(final int returnCode,
				final ArrayList<ListItemEntity> list_latest,
				final ArrayList<ListItemEntity> list_interest,
				final ArrayList<ListItemEntity> list_appreciate,
				final int pageCount) {
			// TODO Auto-generated method stub
			super.finishGetProductAd(returnCode, list_latest, list_interest,
					list_appreciate, pageCount);
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (returnCode == IProtocol.STATUS_CODE_OK_200) {
						if (PageNumber < pageCount) {
							PageNumber += 1;
						} else {
							PageNumber = -1;
						}
						if (list_latest != null && list_latest.size() > 0) {
							arrProduct.addAll(list_latest);

						}
						if (list_interest != null && list_interest.size() > 0) {
							arrProduct.addAll(list_interest);
						}
						if (list_appreciate != null
								&& list_appreciate.size() > 0) {
							arrProduct.addAll(list_appreciate);

						}
						mAdapter.notifyDataSetChanged();
					}
					lv_list_product.onRefreshComplete();
					pb_pg_load.setVisibility(View.GONE);
				}
			});
		}

	}

	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		if (PageNumber > 0) {

			if (refreshView.getCurrentMode() == Mode.PULL_FROM_START){
				PageNumber = 1;
				arrProduct.clear();
				mAdapter.notifyDataSetChanged();
			}
			switch (action) {
			case 0:
				ClassifiedCore.getInstance(this.getApplication()).taskGetAndroidProductAd(mListener, PAGE_LIMIT,
						SortBy, PageNumber, mArea.getRemoteId());
				break;
			case 1:
				String CateID = extras.getString("categoryID");
				ClassifiedCore.getInstance(this.getApplication()).taskGetAndroidProductAd(mListener, PAGE_LIMIT,
						SortBy, PageNumber, mArea.getRemoteId());
				break;
			case 2:
				CateID = extras.getString("CateID");
				String cost = extras.getString("Cost");
				int GuaranteeStoreID = extras.getInt("GuaranteeStoreID");
				String NotInPCodes = extras.getString("NotInPCodes");
				ClassifiedCore.getInstance(ListCateproductActivity.this).taskGetAndroidProductSameCost(mListener, CateID,
						GuaranteeStoreID + "", "", PAGE_LIMIT, PageNumber,"products", false, NotInPCodes, cost);
				break;
			case 3:
				CateID = extras.getString("categoryID");
				GuaranteeStoreID = extras.getInt("GuaranteeStoreID");
				NotInPCodes = extras.getString("NotInPCodes");
				ClassifiedCore.getInstance(ListCateproductActivity.this).taskGetAndroidProductType(mListener, CateID,
						GuaranteeStoreID + "", "", 10, PageNumber,"products", false, NotInPCodes);
				break;

			default:
				break;
			}
		} else {
			new Handler().post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					lv_list_product.onRefreshComplete();
				}
			});
		}
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(isTaskRoot()){

			long triggerSize = 3000000; 
			long targetSize = 2000000;      
			AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
		}
	}
}
